package cn.seaboot.admin.starter.web;

import cn.seaboot.admin.security.jwt.SecurityJwtProperties;
import cn.seaboot.admin.security.jwt.AuthenticationJwt;
import cn.seaboot.admin.security.token.UserToken;
import cn.seaboot.commons.core.Converter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author postm
 */
@Controller
@Tag(name = "FreeMarker全局映射配置")
public class CorePageCtrl {
    private final Logger logger = LoggerFactory.getLogger(CorePageCtrl.class);

    @Resource
    private SecurityJwtProperties securityJwtProperties;

    @Resource
    private SecurityJwtProperties securityJwtConstant;

    /**
     * 匹配任意模版文件
     */
    @RequestMapping(value = "**/*.ftl", method = RequestMethod.GET)
    public void core() {
    }

    /**
     * 匹配任意模版文件
     */
    @RequestMapping(value = "index.ftl", method = RequestMethod.GET)
    public void indexPage(ModelMap modelMap, HttpServletRequest request) {
//        UserToken token = (UserToken) SecurityContextHolder.getContext().getAuthentication();
//        if (token != null) {
//            // 如果上下文中已经存在 token，则直接使用上下文中的
//            logger.debug("[security token filter] using context token: {}", token);
//        } else if (securityJwtProperties.isUsingSession()) {
//            // 使用会话缓存中的账号信息
//            token = (UserToken) request.getSession().getAttribute(securityJwtProperties.getTokenName());
//            if (token != null) {
//                logger.debug("[security token filter] using cache token : {}", token);
//            }
//        }

        // 这里需要增加防止 csrf 攻击的 token
        //        if (token == null) {
        //            throw new AccessDeniedException("access denied!");
        //        } else {
        //            String tokenName = securityJwtConstant.getTokenName();
        //            DefaultCsrfToken csrfToken = new DefaultCsrfToken(tokenName, tokenName, "token");
        //            modelMap.addAttribute("_csrf", csrfToken);
        //        }
    }
}
